package com.xiaomazi.acl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.xiaomazi.acl.entity.User;
import com.xiaomazi.acl.service.PermissionService;
import com.xiaomazi.acl.service.UserService;
import com.xiaomazi.security.entity.SecurityUser;
import com.xiaomazi.servicebase.exception.LLXYException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @program: llxy-parent
 * @description: 认证用户和封装用户权限信息
 * @author: 小马子
 * @create: 2023-03-14 13:17
 **/
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.query().eq("username", username).one();
        if (Objects.isNull(user)){
            throw new LLXYException(20001,"用户名不存在");
        }

        com.xiaomazi.security.entity.User cUser = new com.xiaomazi.security.entity.User();
        BeanUtil.copyProperties(user,cUser);

        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        SecurityUser securityUser = new SecurityUser(cUser, authorities);
        return securityUser;
    }
}
